import request from '../../common/request'
import {wlq} from '../../common/config'
Page({

  data: {
    pickArr: ["默认排序", "最早发布", "最新发布", "价格降序", "价格升序"],
    pickIndex: 0,
    searchValue: "",
    goodList: [],
    tempList: [],
    page: 1,
    size: 10,
    total: 0,

    // 是否加载数据
    notAdd: false,
    // 是否显示暂无商品字样
    isNotGoods:false
  },

  //选择排列顺序
  handleChoose(e) {
    this.setData({
      pickIndex: e.detail.value,
    });
    this.showBySort(e.detail.value);
  },

  // 处理输入值
  handleInput(e) {
    this.setData({
      searchValue: e.detail.value,
    });
  },

  // 清除输入框中的数据
  clearInput() {
    this.setData({
      searchValue: "",
      goodList:[],
      isNotGoods:false,
      notAdd:false
    });
  },

  // 处理点击事件
  async handleSearch() {
    // 在处理搜索事件之前先把状态写好
    this.setData({
      notAdd:false
    })
    let { page, size, searchValue } = this.data;
    page = 1;
    const url = `${wlq}/es/s/${page}/${size}?search=${searchValue}`;

    const {data} = await request(url);

    // console.log('搜索页面',data);

    if(data.list.length<size&&data.list.length!==0){
      // 表示后面没有数据
      this.setData({
        notAdd:true
      })
    }

    this.setData({
      goodList: data.list,
      tempList: data.list,
      page: data.page,
      size: data.size,
      total: data.total,
      isNotGoods:true
    });

    this.setData({
      pickIndex: 0,
    });
  },

  // 按价格排序
  showBySort(num) {
    let { tempList } = this.data;
    tempList.map((item) => (item["time"] = +new Date(item.createTime)));
    if (num == 3) {
      //降序
      tempList.sort((a, b) => b.goodsPrice - a.goodsPrice);
    }
    if (num == 4) {
      //升序
      tempList.sort((a, b) => a.goodsPrice - b.goodsPrice);
    }
    if (num == 1) {
      // 最近发布
      tempList.sort((a, b) => a.time - b.time);
      // console.log("最近发布", tempList);
    }
    if (num == 2) {
      //最晚发布
      tempList.sort((a, b) => b.time - a.time);
    }

    this.setData({
      goodList: tempList,
    });
  },

  // 处理触底加载更多
  async handleScroll() {

    if (this.data.notAdd) {
      return;
    }
    let { page, size, searchValue, tempList } = this.data;
    const url = `${wlq}/es/s/${++page}/${size}?search=${searchValue}`

    const {data} = await request(url);

    if (data.list.length > 0) {
      const dataList = [...tempList, ...data.list];
      this.setData({
        goodList: dataList,
        tempList: dataList,
        page: data.page,
      });
    } else {
      // 当返回的数据是空列表的时候，设置不再加载更多数据
      this.setData({
        notAdd: true,
      });
    }
  },


});
